package top.glkj.hms.algorithm;

import top.glkj.hms.entity.User;
import top.glkj.hms.utils.StaticValue;

import java.util.Date;
import java.util.Random;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2021/3/8 16:47
 */
public final class Order {
    private static int H = 1;
    public synchronized static String getOrderNumber(User user,Date date) {
        long uid = user.getId();
        Random random = new Random();
        int i = random.nextInt(StaticValue.TEN);
        StringBuffer sb = new StringBuffer();
        sb.append(getTimeNumber(date));
        sb.append(decodeId(uid));
        sb.append(i);
        if (H>100000000){
            H = 1;
        }
        sb.append(decodeId(H++));
        return sb.toString();
    }

    private static String  getTimeNumber(Date now) {
        if (now==null){
            now = new Date();
        }
        int year = now.getYear()+1900;
        int month = now.getMonth()+1;
        int day = now.getDate();
        int hour = now.getHours();
        int minutes = now.getMinutes();
        int seconds = now.getSeconds();
        StringBuffer sb = new StringBuffer();
        sb.append(year);
        if (month< StaticValue.TEN){
            sb.append(StaticValue.ZERO);
        }
        sb.append(month);
        if (day< StaticValue.TEN){
            sb.append(StaticValue.ZERO);
        }
        sb.append(day);
        if (hour< StaticValue.TEN){
            sb.append(StaticValue.ZERO);
        }
        sb.append(hour);
        if (minutes< StaticValue.TEN){
            sb.append(StaticValue.ZERO);
        }
        sb.append(minutes);
        if (seconds< StaticValue.TEN){
            sb.append(StaticValue.ZERO);
        }
        sb.append(seconds);
        return sb.toString();
    }

    private static String decodeId(long id) {
        long uid = id % 100000;
        long did = id / 100000;
        StringBuffer sb = new StringBuffer();
        sb.append(did);
        for (int i = 0; i < StaticValue.FIVE-Long.toString(uid).length(); i++) {
            sb.append(0);
        }
        sb.append(uid);

        return sb.toString();
    }
}
